package util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.Normalizer;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.controle;
import org.apache.commons.io.FileUtils;
import org.jasypt.util.text.BasicTextEncryptor;

public final class Tools {

   public static String convertPowerOfByte(long valor, String patern){  
       String[] powerOfByte= {"B","KB","MB","GB","TB"};  
       int potencia=0;  
       int proxima=potencia;  
       boolean testaPotenciaActual;  
       boolean testaPotenciaSeguinte;  
       do {  
           proxima=potencia+1;  
           testaPotenciaActual= (Math.pow(2,potencia*10)<=valor);  
           testaPotenciaSeguinte= (valor<Math.pow(2,proxima*10));  
           potencia++;  
  
       } while(!(testaPotenciaActual && testaPotenciaSeguinte));  
         
       potencia--;  
       DecimalFormat myFormatter = new DecimalFormat(patern);  
         
       return myFormatter.format(valor/Math.pow(2,potencia*10))+" "+powerOfByte[potencia];  
   }  
    
    public static Frame getRootFrame(Component c) {
        Frame ret = null;
        Component c1 = c.getParent();
        while(c1.getParent() != null) {
            c1 = c1.getParent();
        }
        ret = (Frame)c1;
        return ret;        
    } 
    
    public static Long stringDate2Long(String d) {
        Long l = null;
        //"2011-09-21 06:00:00.0"
        String[] parts1 = d.split(" ");
        String[] data = parts1[0].split("-");
        String[] tempo = parts1[1].split(":");
        int ano = Integer.parseInt(data[0]);
        int mes = Integer.parseInt(data[1]);
        mes--;
        int dia = Integer.parseInt(data[2]);
        int hora = Integer.parseInt(tempo[0]);
        int minuto = Integer.parseInt(tempo[1]);
        GregorianCalendar gc = new GregorianCalendar(ano, mes, dia, hora, minuto);
        return gc.getTimeInMillis();
    }

    public static Date DBDate2JavaDate(String dat) {
        try {
            return new Date(stringDate2Long(String2DBDate(dat) + " 00:00:00"));
        } catch (Exception ex) {
            Logger.getLogger(controle.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static String DBDate2String(String dat) throws Exception {
        String[] d = dat.split("-");
        if(d.length != 3) throw new Exception("Data do banco no formato inválido : " + dat);
        return d[2] + "/" + d[1] + "/" + d[0];
    }

    public static String String2DBDate(String dat) {
        String[] d = dat.split("/");
        return d[2] + "-" + d[1] + "-" + d[0];
    }
    
    public static Color stringToColor(final String value) {
        if (value == null) {
            return Color.black;
        }
        try {
            // get color by hex or octal value
            return Color.decode(value);
        } catch (NumberFormatException nfe) {
            // if we can't decode lets try to get it by name
            try {
                // try to get a color by name using reflection
                final Field f = Color.class.getField(value);

                return (Color) f.get(null);
            } catch (Exception ce) {
                // if we can't get any color return black
                return Color.black;
            }
        }
    }
    
    public static String getMD5Hash(String str) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes());
        byte[] retorno = md5.digest();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < retorno.length; i++) {
           int parteAlta = ((retorno[i] >> 4) & 0xf) << 4;
           int parteBaixa = retorno[i] & 0xf;
           if (parteAlta == 0) s.append('0');
           s.append(Integer.toHexString(parteAlta | parteBaixa));
        }
        return s.toString();
    }
    
    public static String getPassByKey(String encpass, String key) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(key);
        String plainText = textEncryptor.decrypt(encpass);
        return plainText;
    }
    
    public static String getEncryptedByKey(String decpass, String key) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(key);
        String enc = textEncryptor.encrypt(decpass);
        return enc;
    }    
    
    public static File parseTemplate(String template, HashMap<String, String> data, boolean genfile) throws IOException  {
        
        String temp = FileUtils.readFileToString(new File(template));
        Set<String> chaves = data.keySet();
        Iterator i = chaves.iterator();
        while(i.hasNext()) {
            String ch = (String)i.next();
            String sb = data.get(ch);
            temp = temp.replaceAll("@@" + ch + "@@", sb);
        }
        File f = new File(template + ".html");
        if(genfile) {
            FileUtils.writeStringToFile(f, temp);
        }
        
        return f;
    }
    
    public static String phrasePreProcessing(String t) {
        String tmp = t.trim();
        tmp = tmp.replaceAll("\\s+", " ");
        tmp = Normalizer.normalize(tmp, Normalizer.Form.NFD);  
        tmp = tmp.replaceAll("[^\\p{ASCII}]", "");         
        return tmp;
    }
    
}